/**
 * Created by shenhai on 15/9/22.
 */


var async = require('async');
var moment = require('moment');
var Community = mongoose.model('community');
var User = mongoose.model('user');
var Question = mongoose.model('question');
var ReplyAt = mongoose.model('question_replyAtService');
var replyAt = mongoose.model('question_replyAt');
var QuestionReport = mongoose.model('question_reports');
var UserFollowups = mongoose.model('user_followups');
var SystemMessage = mongoose.model('system_messages');
var ugcIndex = mongoose.model('system_ugcIndex');
var ugcReply = mongoose.model('system_ugcReply');
var replyIndex = mongoose.model('reply_index');
var QuestionAndReplyCount = mongoose.model('question_replycounts');
var Dic = mongoose.model('masterData_Dictionaries');
var redisKey = require('../../../config/redisKey');
var mysqlUtil = require('../../../common/utils/mysqlUtil');
var toolUtil = require('../../../common/utils/toolUtil');

/*  宝宝树66小区二次改造    add   gct  20170821   start   */
var SystemChatMessages = mongoose.model('system_chatMessages');
/*  宝宝树66小区二次改造    add   gct  20170821   end   */

/*  宝宝树66小区二次改造    add   chenf  20170821   start   追加举报区分闲置和帖子*/
var GoodsReport = mongoose.model('goods_reports');
var Goods = mongoose.model('goods');
/*  宝宝树66小区二次改造    add   chenf  20170821   start   追加举报区分闲置和帖子*/

/*  宝宝树66小区二次改造    add   guo.xiaomin  20170825  start   */
// 置顶，精华，屏蔽
var userService = require('../../userService');
/*  宝宝树66小区二次改造    add   guo.xiaomin  20170825  end   */

exports.questionListService = function(req ,callback) {

    var body = req.body;
    var page = req.params.page;
    var size = Number(req.params.size);
    var index = (Number(req.params.page) - 1) * size;
    var totalPage = 0;

    var option =  {isValid:true,fromFlag:{$ne:'service'}};

    var sortType = body.sort ? {dateLastModified: -1} : {dateCreated: -1};
    if (body.city) option.city = body.city;
    if (body.community) option.community = body.community;
    if (body.desc) option.desc = new RegExp(body.desc);
    if (body.createdBy) option.createdBy = body.createdBy;

    if (body.tag != null) {
        if (body.tag) {
            option['tag'] = {$exists: true, $not: {$size: 0}};
        } else {
            option['$or'] = [{tag:{$exists: false}},{tag:{$size: 0}}];
        }
    };

    if (body.replies) {
        if (body.replies == 'true') {
            option['replies'] = {$exists: true, $not: {$size: 0}};
        } else if(body.replies == 'false'){
            //option['$or'] = [{replies:{$exists: false}},{replies:{$size: 0}}];
            option['replies.0'] = { '$exists': false };
        }
    };
    //logger.debug('replies');
    //logger.debug(option);
    //if (body.level != null) option.level = body.level ? 1 : {$ne: 1};
    if (body.level != null) option.level = body.level ;

    if (body.startDate || body.endDate) {
        if (body.startDate && body.endDate) {
            if (body.startDate < body.endDate) {
                option.dateCreated = {$gte: body.startDate, $lte: body.endDate};
            }
        } else if (body.startDate) {
            option.dateCreated = {$gte: body.startDate};
        } else if (body.endDate) {
            option.dateCreated = {$lte: body.endDate};
        }

    };

    if(body.model){
        if(body.model == 2){
            var time = new Date(new Date().getTime() - 10 * 60 * 1000);
            option.dateCreated ={$lte: time};
        };
    };

    if (body.category) {
        if(body.category == 'question'){
            option['$or'] = [{category:'question'},{category:'lostAndFound'}];
            //option.category = body.category;
        }else if(body.category == 'share'){
            option['$or'] = [{category:'share'},{category:'advertisement'}];
        };
    };

    if(body.cityType){

        if(body.cityType ==-1){
            option.city = {'$nin':[mongoose.Types.ObjectId('54d862bb573a6d301441b94d'),mongoose.Types.ObjectId('54d862bb573a6d301441b94f')]}
        };
    };

    ////是否跨小区显示
    //if (body.aroundCommunity != null) {
    //    if (body.tag) {
    //        option['aroundCommunity'] = {$exists: true, $not: {$size: 0}};
    //    } else {
    //        option['aroundCommunity'] = [{aroundCommunity:{$exists: false}},{aroundCommunity:{$size: 0}}];
    //    };
    //};

    if (body.status) option.status = body.status;

    logger.debug('body:');
    logger.debug(body);

    logger.debug('option:');
    logger.debug(option);

    async.series([

        function (callbackInner) {

            if (body.nickName) {
                User.find({nickName: new RegExp(body.nickName)}, function (err, result) {
                    option.createdBy = {$in:result};
                    callbackInner(err, result);
                });
            }else {
                callbackInner();
            }
        },

        function (callbackInner) {
            Question.count(option, function (err, count) {

                totalPage = Math.ceil(count/size);
                var temp = {count: count, totalPage:totalPage};
                callbackInner(err, temp);

            });
        },
        function (callbackInner) {
            Question.find(option)
                .populate('city', 'name')
                .populate('community', 'communityName')
                .populate('aroundCommunity', '_id communityName')
                .populate('tag', 'value')
                .populate('createdBy', '_id nickName')
                .populate('replies.repliedBy', '_id community nickName images authenticationStatus')
                .sort(sortType).skip(index).limit(size).exec(function (err, result) {

                    if (result) {
                        result.forEach(function (question) {

                            { // 标签
                                var data = new Array();
                                if (question.tag) {
                                    question.tag.forEach(function (t) {
                                        data.push(t.value);
                                    });
                                    question._doc.tag = data;
                                }
                            }


                            //{ // 板块
                            //    var data = new Array();
                            //    if (question.aroundCommunity) {
                            //        question.aroundCommunity.forEach(function (t) {
                            //            data.push(t.communityName);
                            //        });
                            //    }
                            //    question._doc.aroundCommunity = data;
                            //}
                        });
                    }
                    callbackInner(err, result);
                });
        }
    ], callback);

};

exports.updateQuestionService = function(req ,callback) {

    var id = req.body.id;
    var question = req.body.question;
    if (!id || !question) return callback('body错误', null);
    logger.debug(question);
    Question.update({_id:id}, question, callback);
};

exports.setTopQuestionService = function(req ,callback) {

    var body = req.body;
    var id = body.id;

    //需要修改其他置顶帖子的结束时间
    //var question ={
    //    topBeginDate : moment()
    //    ,topEndDate : moment().add(1, 'day')
    //};
    //logger.debug(question);
    if(body.isTop) {

        var option = {};
        /*  宝宝树66小区二次改造    add   chenf  20170731   start   */
        // 置顶flg
        option.topFlg = body.topFlg;
        // 本小区置顶的场合
        if(body.topFlg == 2) {
            /*  宝宝树66小区二次改造    add   chenf  20170731   end   */
            if (body.communityId) option.community = body.communityId;
            if (body.category) option.category = body.category;
        }
        option['topBeginDate'] = {$lte: moment().format('YYYY-MM-DD HH:mm:ss')};
        option['topEndDate'] = {$gte: moment().format('YYYY-MM-DD HH:mm:ss')};
        logger.debug(option);
        Question.find(option).exec(function (err, result) {
            if (result.length) {

                Question.update(option, {topEndDate: moment().format('YYYY-MM-DD HH:mm:ss')},{ multi: true }, function (err, result) {

                    var question ={
                        /*  宝宝树66小区二次改造    add   chenf  20170731   start   */
                        topFlg : body.topFlg,
                        /*  宝宝树66小区二次改造    add   chenf  20170731   end   */
                        topBeginDate : body.beginDate
                        ,topEndDate : body.endDate
                    };
                    logger.debug('更新数：' +result);
                    logger.debug(question);
                    Question.update({_id: id}, question, callback);
                });
            }else{

                logger.debug('没有置顶');
                var question ={
                    /*  宝宝树66小区二次改造    add   chenf  20170731   start   */
                    topFlg : body.topFlg,
                    /*  宝宝树66小区二次改造    add   chenf  20170731   end   */
                    topBeginDate : body.beginDate
                    ,topEndDate : body.endDate
                };
                logger.debug(question);
                Question.update({_id: id}, question, callback);

            };

        });

    }else{

        var question ={
            /*  宝宝树66小区二次改造    add   chenf  20170731   start   */
            topFlg : 0,
            /*  宝宝树66小区二次改造    add   chenf  20170731   end   */
            topBeginDate : null
            ,topEndDate : null
        };
        Question.update({_id: id}, question, callback);
    };

};

exports.deleteQuestionService = function(req ,callback) {

    // 删帖额外处理

    var id = req.body.questionId;
    if (!id)  return callback('body错误', null);

    var body = req.body;

    restClient.delete('http://' + AppHost + '/rest/v1.0/backoffice/admin/deleteQuestion/' + id, function (data, response) {

        var tokenData = JSON.parse(data);

        logger.debug(tokenData);

        if (tokenData.result.status == 1) {

            var arg = {
                userId: body.userId + '',
                userRole: Number(body.userRole),
                userActionType:  Number(body.category)
            };

            arg.__type__ = 'com.neighborhoods.service.score.dto.ScoreAddRequestDto';
            logger.debug(arg);
            scoreProxy.invoke('addScore', [arg], function (err, reply) {
                try {
                    logger.debug(reply);
                    var data = JSON.parse(decodeURIComponent(reply));
                    if (err) {
                        logger.error('hessianInvokeAddScore-----2' + err.message);
                        callback(null);
                    } else if (data.status != 0) {
                        logger.error('hessianInvokeAddScore----3' + data.status + '----' + data.msg);
                        callback(null);
                    } else {
                        callback(null);
                    }
                } catch (e) {
                    logger.error('hessianInvokeAddScore---4' + e);
                    callback(e);
                }
            });
        };

    });

};

exports.shieldQuestionService = function(req ,callback) {

    var body = req.body;
    var id = body.questionId;
    logger.debug(body);
    /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170825  start   */
    var userId =  body.userId;
    /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170825  end   */

    if(body.isShow==true || body.isShow =='true' ) {
        Question.update({_id: id}, {isShow: -1}, callback);
        /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170825  start   */
        // shielding:屏蔽
        userService.incModeratorManager(userId, 'shielding', 1, null);
        userService.saveModeratorManagerOperationNote(userId, id, '屏蔽', null);
        /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170825  end   */
    }else{
        Question.update({_id: id}, {$unset:{isShow:-1}}, callback);
        /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170825  start   */
        // shielding:屏蔽
        userService.incModeratorManager(userId, 'shielding', -1, null);
        userService.saveModeratorManagerOperationNote(userId, id, '取消屏蔽', null);
        /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170825  end   */
    };

};

exports.acrossCityQuestionService = function(req ,callback) {

    var body = req.body;
    var id = body.questionId;
    logger.debug(body);

    if(body.acrossCity==true || body.acrossCity =='true' ) {
        Question.update({_id: id}, {acrossCity: 1}, callback);
    }else{
        Question.update({_id: id}, {$unset:{acrossCity:1}}, callback);
    };

};
//获取导出数据
exports.questionService = function(req ,callback) {

    var body = req.cparams;

    var option =  {isValid:true,fromFlag:{$ne:'service'}};

    var sortType = body.sort ? {dateLastModified: -1} : {dateCreated: -1};
    if (body.city) option.city = body.city;
    if (body.community) option.community = body.community;
    if (body.desc) option.desc = new RegExp(decodeURI(body.desc));
    if (body.createdBy) option.createdBy = body.createdBy;

    //if (body.tag != null) {
    //    if (body.tag) {
    //        option['tag'] = {$exists: true, $not: {$size: 0}};
    //    } else {
    //        option['$or'] = [{tag:{$exists: false}},{tag:{$size: 0}}];
    //    }
    //}

    if (body.replies) {
        if (body.replies == 'true') {
            option['replies'] = {$exists: true, $not: {$size: 0}};
        } else if(body.replies == 'false'){
            //option['$or'] = [{replies:{$exists: false}},{replies:{$size: 0}}];
            option['replies.0'] = { '$exists': false };
        }
    }
    //logger.debug('replies');
    //logger.debug(option);
    //if (body.level != null) option.level = body.level ? 1 : {$ne: 1};
    if (body.level != null) option.level = body.level ;

    if (body.startDate || body.endDate) {
        if (body.startDate && body.endDate) {
            if (decodeURI(body.startDate) < decodeURI(body.endDate)) {
                option.dateCreated = {$gte: decodeURI(body.startDate), $lte: decodeURI(body.endDate)};
            }
        } else if (body.startDate) {
            option.dateCreated = {$gte: decodeURI(body.startDate)};
        } else if (body.endDate) {
            option.dateCreated = {$lte: decodeURI(body.endDate)};
        };

    };

    if(body.model){
        if(body.model == 2){
            var time = new Date(new Date().getTime() - 10 * 60 * 1000);
            option.dateCreated ={$lte: time};
        };
    };

    if (body.category) {
        if(body.category == 'question'){
            option['$or'] = [{category:'question'},{category:'lostAndFound'}];
            //option.category = body.category;
        }else if(body.category == 'share'){
            option['$or'] = [{category:'share'},{category:'advertisement'}];
        };
    };

    if(body.cityType){

        if(body.cityType ==-1){
            option.city = {'$nin':[mongoose.Types.ObjectId('54d862bb573a6d301441b94d'),mongoose.Types.ObjectId('54d862bb573a6d301441b94f')]}
        };
    };

    if (body.status) option.status = body.status;

    logger.debug('body:');
    logger.debug(body);

    logger.debug('option:');
    logger.debug(option);

    async.series([

        function (callbackInner) {

            if (body.nickName) {
                User.find({nickName: new RegExp(decodeURI(body.nickName))}, function (err, result) {
                    option.createdBy = {$in:result};
                    callbackInner(err, result);
                });
            }else {
                callbackInner();
            }
        },
        //function (callbackInner) {
        //    Question.count(option, function (err, count) {
        //
        //        totalPage = Math.ceil(count/size);
        //        var temp = {count: count, totalPage:totalPage};
        //        callbackInner(err, temp);
        //
        //    });
        //},
        function (callbackInner) {
            Question.find(option)
                .populate('community', 'communityName')
                .populate('aroundCommunity', '_id communityName')
                .populate('tag', 'value')
                .populate('createdBy', '_id nickName mobilePhone')
                .populate('replies.repliedBy', '_id community nickName images authenticationStatus')
                .sort(sortType).exec(function (err, result) {

                    if (result) {
                        result.forEach(function (question) {

                            { // 标签
                                var data = new Array();
                                if (question.tag) {
                                    question.tag.forEach(function (t) {
                                        data.push(t.value);
                                    });
                                    question._doc.tag = data;
                                }
                            }


                            //{ // 板块
                            //    var data = new Array();
                            //    if (question.aroundCommunity) {
                            //        question.aroundCommunity.forEach(function (t) {
                            //            data.push(t.communityName);
                            //        });
                            //    }
                            //    question._doc.aroundCommunity = data;
                            //}
                        });
                    }
                    callbackInner(err, result);
                });
        }
    ], callback);

};


// 待处理，或删除
exports.replyListService = function(req ,callback) {

    var id = req.body.id;
    if (!id)  return callback('body错误', null);

    Question.findOne({_id:id}, 'replies.replyDesc replies.repliedBy replies.community replies.dateReplied')
        .populate('replies.repliedBy', '_id nickName')
        .populate('replies.community', '_id communityName')
        .exec(function(err, question) {

        if (!question.replies) {
            callback();
        }else {

            async.each(question.replies, function(repliy, callback){
                var communityName = '';
                if (repliy.repliedBy.nickName != '小6客服') {
                    communityName = arry[repliy.repliedBy.community]['communityName'];
                }
                repliy.repliedBy._doc['communityName'] = communityName;

                replyAt.findOne({replyId: repliy._id + ''}, function (err, at) {
                    if (at != null && at.uList != null) {
                        at.uList.forEach(function (temp, i) {
                            if(temp.nickName != undefined)repliy.replyDesc = repliy.replyDesc.replace(new RegExp("@\\{" + i + "\\}"), '@' + temp.nickName + ' ')
                        });
                    }
                    callback(null);// must call once
                }).populate('uList', '_id nickName');

            }, function(err){
                callback(null);// must call once
            });
        }

    });
};

exports.replyAtListService = function(req ,callback) {

// community  status

    var body = req.body;
    var page = req.params.page;
    var size = Number(req.params.size);
    var index = (Number(req.params.page) - 1) * size;
    var totalPage = 0;

    var option = body;
    var sortType = {dateCreated: -1};



    async.series([


        function (callbackInner) {
            ReplyAt.count(option, function (err, count) {

                totalPage = Math.ceil(count/size);
                var temp = {count: count, totalPage:totalPage};
                callbackInner(err, temp);

            });
        },

        function (callbackInner) {
            ReplyAt.find(option)
                .populate('atUser', 'nickName')
                .populate('community', 'communityName')
                .sort(sortType).skip(index).limit(size).exec(function (err, result) {

                    if (result) {
                        async.each(result, function (temp, callbackInner) {
                            replyAt.findOne({replyId: temp._doc.replyId + ''}, function (err, at) {
                                if (at != null && at.uList != null) {
                                    at.uList.forEach(function (u, i) {
                                        if (temp._doc.content != null)
                                            temp._doc.content = temp._doc.content.replace(new RegExp("@\\{" + i + "\\}"), '@' + u.nickName + ' ')
                                    });
                                }
                                callbackInner();
                            }).populate('uList', '_id nickName');
                        }, function (err) {
                            callbackInner(err, result);
                        })
                    } else {
                        callbackInner(err, result);
                    }

                });
        }

    ], callback);

};

/*  宝宝树66小区二次改造    add   gct  20170821   start   */
exports.personalLetterAtListService = function(req ,callback) {

// community  status

    var body = req.body;
    var page = req.params.page;
    var size = Number(req.params.size);
    var index = (Number(req.params.page) - 1) * size;
    var totalPage = 0;

    var option = body;
    var sortType = {dateCreated: -1};



    async.series([


        function (callbackInner) {
            SystemChatMessages.count(option, function (err, count) {

                totalPage = Math.ceil(count/size);
                var temp = {count: count, totalPage:totalPage};
                callbackInner(err, temp);

            });
        },

        function (callbackInner) {
            SystemChatMessages.find(option)
                .sort(sortType).skip(index).limit(size).exec(function (err, result) {

                if (result) {
                    async.each(result, function (temp, callbackInner) {
                        User.findOne({mobilePhone: temp._doc.from + ''}, function (err, at) {
                            if (at != null) {
                                temp._doc.from=at._doc.nickName;
                                temp._doc.__v=at._doc._id;
                               /* at.uList.forEach(function (u, i) {
                                    if (temp._doc.content != null)
                                        temp._doc.content = temp._doc.content.replace(new RegExp("@\\{" + i + "\\}"), '@' + u.nickName + ' ')
                                });*/
                            }
                            callbackInner();
                        });
                    }, function (err) {
                        callbackInner(err, result);
                    })
                } else {
                    callbackInner(err, result);
                }
              /*  callbackInner(err, result);*/
            });
        }

    ], callback);

};

/*  宝宝树66小区二次改造    add   gct  20170821   end   */


exports.replyAtUpdateService = function(req ,callback) {

    ReplyAt.update({_id:req.body.id}, {status:req.body.status}, callback);
};

exports.questionReportListService = function(req ,callback) {
    var data = new Array();
    var body = req.body;
    var page = req.params.page;
    var size = Number(req.params.size);
    var index = (Number(req.params.page) - 1) * size;
    var totalPage = 0;

    var sortType = {dateCreated: -1};

    logger.debug(body);

    var option = {};

    /*  宝宝树66小区二次改造    add   guo.xiaomin  20170829   start   */
    if(body.community) {
        option.questionCommunity = body.community;
    }
    /*  宝宝树66小区二次改造    add   guo.xiaomin  20170829   start   */

    //opt.status = false;
    //if(req.body.status)option.status = req.body.status;
    if(body.reportStatus != null ) {
        if(body.reportStatus == 0){
            option['$or'] = [{reportStatus:0},{reportStatus:{$exists: false}}];
        }else {
            option.reportStatus = body.reportStatus;
        }
    }
    logger.debug(option);
    async.series([

        function (callbackInner) {
            /*  宝宝树66小区二次改造    mod   gct  20170901   start   */
           /* QuestionReport.count(option, function (err, count) {

                    totalPage = Math.ceil(count/size);
                    var temp = {count: count, totalPage:totalPage};
                    callbackInner(err, temp);  旧*/

            if (body.communityValue) {
                Community.findOne({
                    communityName: req.body.communityValue,
                    isValid: true,
                    cityId: req.body.city
                }, function (err, result) {

                     if (result == null) {
                        return callback({status: 999, message: "请仔细确认小区名"}, null);
                    }
                     else {
                         option.questionCommunity = result._id;
                         QuestionReport.count(option, function (err, count) {

                             totalPage = Math.ceil(count / size);
                             var temp = {count: count, totalPage: totalPage};
                             callbackInner(err, temp);

                         });
                     }
                });
            }
            else {
                QuestionReport.count(option, function (err, count) {

                    totalPage = Math.ceil(count/size);
                    var temp = {count: count, totalPage:totalPage};
                    callbackInner(err, temp);

                });
            }
            /*  宝宝树66小区二次改造    mod   gct  20170901   end   */
        },
        function (callbackInner) {

            QuestionReport.find(option)
                .populate('question', 'community createdBy title desc dateCreated')
                .populate('questionCommunity', '_id communityName')
                .populate('questionCreateBy', '_id nickName')
                .populate('reportUser', 'nickName')
                .sort(sortType).skip(index).limit(size).exec(function (err, results) {

                    data = results;
                    callbackInner(err, results);
                });

        },
        function (callbackInner) {

            async.each(data, function (report, callbackInner2) {

                QuestionReport.count({question: report.question}, function (err, count) {
                    if (report && count != null) {
                        report._doc['count'] = count;
                    }
                    callbackInner2();
                });

            }, function (err) {
                callbackInner(err, null);
            });
        }

    ], callback);





    //QuestionReport.distinct("question",opt, function (err, results) {
    //    async.each(results, function (questionId, callback) {
    //        if (communityId == '1') {
    //            Question.findOne({
    //                _id: questionId
    //            }, 'desc community replies createdBy dateCreated').populate('createdBy', '_id nickName').populate('community', '_id communityName').exec(function (err, result) {
    //                QuestionReport.count({question: questionId}, function (err, count) {
    //                    //logger.debug(questionId);
    //                    //logger.debug(result);
    //                    if (result != null) {
    //                        result._doc['count'] = count;
    //                        data.push(result);
    //                    }
    //                    callback();
    //                })
    //
    //            })
    //        } else {
    //            Question.findOne({
    //                community: communityId,
    //                _id: questionId
    //            }, 'desc community replies createdBy dateCreated').populate('createdBy', '_id nickName').populate('community', '_id communityName').exec(function (err, result) {
    //                QuestionReport.count({question: questionId}, function (err, count) {
    //                    if (result != null) {
    //                        result._doc['count'] = count;
    //                        data.push(result);
    //                    }
    //                    callback();
    //                })
    //            })
    //        }
    //    }, function (err) {
    //        if (err) {
    //            var msg = {
    //                "message": "get err"
    //            };
    //            callback(msg, null);
    //        } else {
    //            data.sort(function (a, b) {
    //                return b.dateCreated - a.dateCreated;
    //            });
    //            callback(null, data);
    //        }
    //    })
    //});

};
/*  宝宝树66小区二次改造    add   chenf  20170821   start   追加举报区分闲置和帖子*/
// 举报闲置内容
exports.goodsReportListService = function(req ,callback) {
    var data = new Array();
    var body = req.body;
    var page = req.params.page;
    var size = Number(req.params.size);
    var index = (Number(req.params.page) - 1) * size;
    var totalPage = 0;
    var sortType = {dateCreated: -1};
    logger.debug(body);
    var option = {};

    /*  宝宝树66小区二次改造    add   gct 20170901   start   */
    if(body.community) {
        option.goodsCommunity = body.community;
    }
    /*  宝宝树66小区二次改造    add   gct  20170901   end   */

    if(body.reportStatus != null ) {
        if(body.reportStatus == 0){
            option['$or'] = [{reportStatus:0},{reportStatus:{$exists: false}}];
        }else {
            option.reportStatus = body.reportStatus;
        }
    }



    logger.debug(option);
    async.series([
        function (callbackInner) {
            /*  宝宝树66小区二次改造    mod   gct  20170901   start   */

            /* GoodsReport.count(option, function (err, count) {

             totalPage = Math.ceil(count/size);
             var temp = {count: count, totalPage:totalPage};
             callbackInner(err, temp);
             }); 旧*/

            if (body.communityValue) {
                Community.findOne({
                    communityName: req.body.communityValue,
                    isValid: true,
                    cityId: req.body.city
                }, function (err, result) {

                    if (result == null) {
                        return callback({status: 999, message: "请仔细确认小区名"}, null);
                    }
                    else {
                        option.goodsCommunity = result._id;
                        GoodsReport.count(option, function (err, count) {

                            totalPage = Math.ceil(count / size);
                            var temp = {count: count, totalPage: totalPage};
                            callbackInner(err, temp);

                        });
                    }
                });
            }
            else {
                GoodsReport.count(option, function (err, count) {

                    totalPage = Math.ceil(count/size);
                    var temp = {count: count, totalPage:totalPage};
                    callbackInner(err, temp);

                });
            }
            /*  宝宝树66小区二次改造    mod   gct  20170901   end   */

        },
        function (callbackInner) {

            GoodsReport.find(option)
                .populate('goods', 'community createdBy title desc dateCreated images')
                .populate('goodsCommunity', '_id communityName')
                .populate('goodsCreateBy', '_id nickName')
                .populate('reportUser', 'nickName')
                .sort(sortType).skip(index).limit(size).exec(function (err, results) {

                data = results;
                callbackInner(err, results);
            });

        },
        function (callbackInner) {

            async.each(data, function (report, callbackInner2) {

                GoodsReport.count({goods: report.goods}, function (err, count) {
                    if (report && count != null) {
                        report._doc['count'] = count;
                    }
                    callbackInner2();
                });

            }, function (err) {
                callbackInner(err, null);
            });
        }

    ], callback);
};
/*  宝宝树66小区二次改造    add   chenf  20170821   end   追加举报区分闲置和帖子*/
exports.deleteQuestionReportService = function (req, callback) {
    /*  宝宝树66小区二次改造    add   chenf  20170821   end   追加举报区分闲置和帖子*/
    /*var questionId = req.body.question;*/
    var objId = req.body._id;
    var statusFlg = req.body.statusFlg;
    // 删除帖子
    if(statusFlg == 1){
        async.series([
            function (callbackInner) {
                Question.update({_id:objId}, {isValid: false}, callbackInner);;
            },
            function (callbackInner) {
                logger.debug(objId);
                QuestionReport.update({question: objId},{reportStatus:1},{upsert:true,multi : true}, callbackInner);
            },
            function (callbackInner) {

                QuestionReport.find({question:objId}).sort({dateCreated: 1}).exec(function (err, results) {
                    logger.debug(results);
                    toolUtil.addScoreMessage(results[0].reportUser.toString(), 1, 6);
                    callbackInner(err, results);
                });

            },
        ], callback);
    }else{
        // 删除闲置
        async.series([
            function (callbackInner) {
                Goods.update({_id:objId}, {isValid: false}, callbackInner);;
            },
            function (callbackInner) {
                logger.debug(objId);
                GoodsReport.update({goods: objId},{reportStatus:1},{upsert:true,multi : true}, callbackInner);
            },
            function (callbackInner) {

                GoodsReport.find({goods:objId}).sort({dateCreated: 1}).exec(function (err, results) {
                    logger.debug(results);
                    toolUtil.addScoreMessage(results[0].reportUser.toString(), 1, 6);
                    callbackInner(err, results);
                });

            },
        ], callback);
    }
    /*async.series([
        function (callbackInner) {
            Question.update({_id:questionId}, {isValid: false}, callbackInner);;
        },
        function (callbackInner) {
            logger.debug(questionId);
            QuestionReport.update({question: questionId},{reportStatus:1},{upsert:true,multi : true}, callbackInner);
        },
        function (callbackInner) {

            QuestionReport.find({question:questionId}).sort({dateCreated: 1}).exec(function (err, results) {
                logger.debug(results);
                toolUtil.addScoreMessage(results[0].reportUser.toString(), 1, 6);
                callbackInner(err, results);
            });

        },
    ], callback);*/

    /*  宝宝树66小区二次改造    add   chenf  20170821   end   追加举报区分闲置和帖子*/
};

exports.rejectQuestionReportService = function (req, callback) {
    /*  宝宝树66小区二次改造    add   chenf  20170821   start   追加举报区分闲置和帖子*/
    /*var questionId = req.body.question;*/
    var objId = req.body._id;
    var statusFlg = req.body.statusFlg;
    // 删除帖子
    if(statusFlg == 1) {
        async.series([
            function (callbackInner) {
                QuestionReport.update({question: objId}, {reportStatus: -1}, {
                    upsert: true,
                    multi: true
                }, callbackInner);
            }
        ], callback);
    }else{
        async.series([
            function (callbackInner) {
                GoodsReport.update({goods: objId}, {reportStatus: -1}, {
                    upsert: true,
                    multi: true
                }, callbackInner);
            }
        ], callback);
    }
    /*async.series([
        function (callbackInner) {
            QuestionReport.update({question: objId}, {reportStatus: -1}, {
                upsert: true,
                multi: true
            }, callbackInner);
        }
    ], callback);*/
    /*  宝宝树66小区二次改造    add   chenf  20170821   end   追加举报区分闲置和帖子*/
};

exports.ignoreQuestionReportService = function (req, callback) {

    var id = req.body.id;
    QuestionReport.remove({_id:id}, callback);
};

exports.questionPushListService = function(req ,callback) {

    var body = req.body;
    var page = req.params.page;
    var size = Number(req.params.size);
    var index = (Number(req.params.page) - 1) * size;
    var totalPage = 0;

    var option = {};


    logger.debug('body:');
    logger.debug(body);

    //logger.debug('option:');
    //logger.debug(option);

    async.series([

        function (callbackInner) {

            var sql = "select count(*) count from 66xiaoqu_rec.smartpush_new order by dateCreated desc";

            mysqlUtil.queryBI(sql, function (err, result) {

                totalPage = Math.ceil(result[0].count / size);
                var temp = {count: result[0].count, totalPage: totalPage};
                callbackInner(err, temp);

            });
        },

        function (callbackInner) {

            var sql =" select * from 66xiaoqu_rec.smartpush_new order by dateCreated desc";
                sql +=" limit " + index +"," + size;

            mysqlUtil.queryBI(sql, function (err, result) {

                if(result && result.length>0) {

                    var queryUserIn = {};
                    queryUserIn["$in"] = [];
                    for (var i = 0, l = result.length; i < l; i++) {
                        queryUserIn["$in"].push(result[i]['_id']);
                    };

                    option["_id"] = queryUserIn;
                    logger.debug('option:');
                    logger.debug(option);

                    Question.find(option)
                        .populate('community', 'communityName')
                        //.populate('aroundCommunity', '_id communityName')
                        .populate('createdBy', '_id nickName')
                        //.populate('replies.repliedBy', '_id community nickName images authenticationStatus')
                        .sort({dateCreated: -1}).exec(function (err, result) {

                            callbackInner(err, result);
                        });

                }else{
                    callbackInner(null, {});
                }


            });


        }

    ], callback);

};

exports.questionPushService = function(req ,callback){

    var ip = req.headers['X-Real-IP'];
    var body = req.body;
    logger.debug(body);
    var option = {};

    //Community.find({_id: body.community}, function(err, result) {

        var queryUserIn = {};
        queryUserIn["$in"] = [];
        //for (var i = 0, l = results.length; i < l; i++) {
        for (var i = 0, l = body.aroundCommunity.length; i < l; i++) {
            queryUserIn["$in"].push(body.aroundCommunity[i]['_id']);
        };
        //queryUserIn["$in"] = body.aroundCommunity;
        option["community"] = queryUserIn;
        logger.debug('option:');
        logger.debug(option);

        User.find(option).exec(function (err, result) {

            logger.debug(result.length);
            var userList = [];
            result.forEach(function (user) {
                userList.push(user._id);
            });

            var content = {
                type: 1,
                flag: 2,
                openType: body.openType,
                contentId: body.contentId,
                createdBy: body.createdBy,
                desc: body.message
                //url: input.url
            };

            var pushData = {
                uList: userList,
                content: content,
                ip:ip,
                tag: body.tag,
                type: 'operate',
                msgType:2
            };
            //logger.debug(pushData);
            toolUtil.putMessageGetuiPushMQ(pushData);

            callback();

        });


    //});



};

exports.questionReplyListService = function(req ,callback) {

    var body = req.body;
    var page = req.params.page;
    var size = Number(req.params.size);
    var index = (Number(req.params.page) - 1) * size;
    //var totalPage = 0;

    var option = {};

    //if(body.replyDesc) {
    //    option = {'replies.replyDesc': new RegExp(body.replyDesc)}
    //}
    if(body.replyBy){
        option = {repliedBy:body.replyBy}
    }

    if(body.replyStatus){
        option = {replyStatus:body.replyStatus}
    }
    //if(body.desc && body.replyBy) {
    //
    //    option = {
    //         'replies.replyDesc': new RegExp(body.replyDesc)
    //        ,'replies.replyBy': body.replyBy
    //    }
    //}
    logger.debug((option));

    async.series([

        function (callbackInner) {
            replyIndex.count(option, function (err, count) {

                if (err) {
                    callbackInner(err, null);
                }else {
                    var temp = {count: count, totalPage:Math.ceil(count/size)};
                    callbackInner(err, temp);
                }
            });
        },
        function (callbackInner) {

            replyIndex.find(option).sort({dateReplied:-1}).skip(index).limit(size)
                .populate('repliedBy', '_id nickName')
                //.populate('createdBy', '_id nickName')
                .populate('community', '_id communityName')
                .exec(function (err, results) {

                    if (results) {

                        async.each(results, function (reply, callbackInner2) {

                            Question.find({_id: reply.contentId}).populate('community', '_id communityName').exec(function (err, result) {

                                    reply._doc['desc'] = result[0].desc;
                                    reply._doc['communityName'] = result[0].community.communityName;

                                Question.find({'replies._id': reply.replyId}).populate('community', '_id communityName').exec(function (err, result2) {

                                    if(result2[0]) {
                                        for (var i = 0; i < result2[0].replies.length; i++) {
                                            if (result2[0].replies[i]._id == reply.replyId) {
                                                reply._doc['replyDesc'] = result2[0].replies[i].replyDesc;
                                            }
                                        }
                                        ;
                                    };
                                    callbackInner2();
                                })
                            });
                        }, function (err) {
                            callbackInner(err, results);
                        });

                    } else {
                        callbackInner(err, results);
                    }






                    //
                    //if (err) {
                    //    callbackInner(err);
                    //} else {
                    //    callbackInner(null, results);
                    //}
                });

        }], callback);
}

/**
 * 删除回答
 */
exports.deleteReplyService = function (req ,callback) {

    var body = req.body;

    //logger.debug(body);
    //toolUtil.getUserByToken(req.body.replyBy, function (err, user) {
    //    if (err) {
    //        callback(err, null);
    //    } else {
    async.series([
        function (callbackInner) {
            Question.update({_id: body.contentId}, {
                $pull: {
                    replies: {
                        _id: body.replyId
                    }
                }
            }).exec(callbackInner);
        },
        function (callbackInner) {
            ugcReply.remove({replyId: body.replyId}, callbackInner);
        },
        function (callbackInner) {
            Question.findOne({_id: body.contentId}, 'category community createdBy', function (err, result) {
                logger.debug(result.community);
                logger.debug(result.category);
                if (result.category != null)
                    redisClient.hincrby('q:count:' + result.community, result.category + 'ReplyCount', -1);
                callbackInner(null, result);
            })
        },
        function (callbackInner) {
            replyIndex.remove({replyId: body.replyId}, callbackInner);
        }
    ], callback);

    //    }
    //})
};


